package Net

import (
	"bytes"
	"encoding/binary"
	"errors"
	"github.com/sentiger/ftcp/Iface"
	"github.com/sentiger/ftcp/Utils"
)

type DataPack struct {
}

func NewDataPack() *DataPack {
	return &DataPack{}
}

// 获取包头的长度
func (dp *DataPack) GetHeadLen() uint32 {
	return 8
}

// 打包过程
func (dp *DataPack) Pack(msg Iface.IMessage) ([]byte, error) {
	dataBuff := bytes.NewBuffer([]byte{})
	// 写入dataLen
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetDataLen()); err != nil {
		return nil, err
	}

	// 写入msgId
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}
	// 写入data
	if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}

	return dataBuff.Bytes(), nil

}

func (dp *DataPack) UnPack(binaryData []byte) (Iface.IMessage, error) {
	dataBuff := bytes.NewReader(binaryData)

	msg := &Message{}
	// 读取消息长度
	if err := binary.Read(dataBuff, binary.LittleEndian, &msg.DataLen); err != nil {
		return nil, err
	}
	// 读取消息id
	if err := binary.Read(dataBuff, binary.LittleEndian, &msg.Id); err != nil {
		return nil, err
	}

	if Utils.GlobalObject.MaxPacketSize > 0 && msg.DataLen > Utils.GlobalObject.MaxPacketSize {
		return nil, errors.New("Too large msg data recieved")
	}
	return msg, nil
}
